package com.mti.monitor.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mti.monitor.bean.PageableIn;
import com.mti.monitor.bean.model.MonitorLogParam;
import com.mti.monitor.bean.model.MonitorPage;
import com.mti.monitor.bean.model.SysMonitorConfig;
import com.mti.monitor.bean.model.SysMonitorErrorLog;
import com.mti.monitor.bean.req.MonitorReq;
import com.mti.monitor.config.properties.Constants;
import com.mti.monitor.enums.TaskTypeEnum;
import com.mti.monitor.mapper.SysMonitorConfigMapper;
import com.mti.monitor.scheduled.ScheduledConfig;
import com.mti.monitor.service.SysMonitorConfigService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Service
@Log4j2
public class SysMonitorConfigServiceImpl implements SysMonitorConfigService {

    @Autowired
    private SysMonitorConfigMapper sysMonitorConfigMapper;

    @Autowired
    private ScheduledConfig scheduledConfig;

    /**
     * 添加配置
     *
     * @param config
     */
    @Override
    public void createConfig(SysMonitorConfig config) {
        config.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        config.setDeleteYn(false);
        config.setCreateTime(new Date());
        if (config.getUseYn()) {
            List<SysMonitorConfig> sysMonitorConfigs = sysMonitorConfigMapper.selectAllList();
            sysMonitorConfigs.add(config);
            //如果是服务类监控，主动增加每6小时监控该服务是否正常
            if (config.getTaskType().equals(TaskTypeEnum.SERVER.getType())) {
                SysMonitorConfig configExt = new SysMonitorConfig();
                BeanUtils.copyProperties(config, configExt);
                configExt.setId(configExt.getId() + Constants.TASK_NAME_EXT);
                configExt.setScheduledCron(Constants.TASK_EXT_CRON);
                sysMonitorConfigs.add(configExt);
            }
            scheduledConfig.refresh(sysMonitorConfigs);
        }
        sysMonitorConfigMapper.insert(config);
    }

    /**
     * 查询所有未删除的数据列表
     *
     * @return
     */
    @Override
    public PageInfo<SysMonitorConfig> selectAllList(PageableIn req) {
        return PageHelper.startPage(req.getCurrPage(), req.getPageSize()).doSelectPageInfo(() -> {
            sysMonitorConfigMapper.selectAllList();
        });
    }

    @Override
    public SysMonitorConfig selectById(String id) {
        return sysMonitorConfigMapper.selectById(id);
    }

    @Override
    public PageInfo<SysMonitorConfig> selectMonitorConfigPage(MonitorReq req) {
        return PageHelper.startPage(req.getCurrPage(), req.getPageSize()).doSelectPageInfo(() -> {
            sysMonitorConfigMapper.selectPage(req);
        });
    }

    @Override
    public List<SysMonitorErrorLog> selectMonitorLogList() {
        return sysMonitorConfigMapper.selectAllLogList();
    }

    /**
     * 分页查询监控配置
     *
     * @param page
     * @return
     */
    @Override
    public MonitorPage selectMonitorLogPage(MonitorLogParam page) {
        int total = sysMonitorConfigMapper.selectLogCount(page.getBeginTime(), page.getEndTime(), page.getKeyWord());
        List list = sysMonitorConfigMapper.selectLogPage((page.getStart() - 1) * page.getSize(), page.getSize(),
                page.getBeginTime(), page.getEndTime(), page.getKeyWord());
        page.setTotal(total);
        page.setList(list);
        return page;
    }

    /**
     * 更新配置
     *
     * @param config
     */
    @Override
    public void updateConfig(SysMonitorConfig config) {
        sysMonitorConfigMapper.updateById(config);
        if ((config.getUseYn() != null && config.getUseYn()) || (config.getScheduledCron() != null)) {
            List<SysMonitorConfig> sysMonitorConfigs = sysMonitorConfigMapper.selectAllList();
            sysMonitorConfigs.add(config);
            //如果是服务类监控，主动增加每6小时监控该服务是否正常
            if (config.getTaskType().equals(TaskTypeEnum.SERVER.getType())) {
                SysMonitorConfig configExt = new SysMonitorConfig();
                BeanUtils.copyProperties(config, configExt);
                configExt.setId(config.getId() + Constants.TASK_NAME_EXT);
                configExt.setScheduledCron(Constants.TASK_EXT_CRON);
                sysMonitorConfigs.add(configExt);
            }
            scheduledConfig.refresh(sysMonitorConfigs);
        } else if (config.getUseYn() != null && !config.getUseYn()) {
            List<String> sysMonitorConfigs = new ArrayList<>();
            sysMonitorConfigs.add(config.getId());
            //如果是服务类监控，主动取消每6小时监控该服务是否正常
            if (config.getTaskType().equals(TaskTypeEnum.SERVER.getType())) {
                sysMonitorConfigs.add(config.getId() + Constants.TASK_NAME_EXT);
            }
            scheduledConfig.stop(sysMonitorConfigs);
        }
    }

    @Override
    public void deleteMonitor(String id) {
        SysMonitorConfig config = sysMonitorConfigMapper.selectById(id);
        config.setUseYn(false);
        config.setDeleteYn(true);
        sysMonitorConfigMapper.updateById(config);

        List<String> sysMonitorConfigs = new ArrayList<>();
        sysMonitorConfigs.add(id);
        //如果是服务类监控，主动取消每6小时监控该服务是否正常
        if (config.getTaskType().equals(TaskTypeEnum.SERVER.getType())) {
            sysMonitorConfigs.add(config.getId() + Constants.TASK_NAME_EXT);
        }
        scheduledConfig.stop(sysMonitorConfigs);
    }

    /**
     * 停用监控
     *
     * @param ids
     */
    @Override
    public void stopMonitor(List<String> ids) {
        List<String> idsExt = new ArrayList<>();
        for (String e : ids) {
            SysMonitorConfig config = sysMonitorConfigMapper.selectById(e);
            config.setUseYn(false);
            sysMonitorConfigMapper.updateById(config);
            //如果是服务类监控，主动取消每6小时监控该服务是否正常
            if (config.getTaskType().equals(TaskTypeEnum.SERVER.getType())) {
                idsExt.add(config.getId() + Constants.TASK_NAME_EXT);
            }
        }
        ids.addAll(idsExt);
        scheduledConfig.stop(ids);
    }

    /**
     * 启用监控
     *
     * @param ids
     */
    @Override
    public void startMonitor(List<String> ids) {
        for (String e : ids) {
            SysMonitorConfig config = sysMonitorConfigMapper.selectById(e);
            config.setUseYn(true);
            sysMonitorConfigMapper.updateById(config);
        }
        List<SysMonitorConfig> sysMonitorConfigs = sysMonitorConfigMapper.selectAllList();
        List<SysMonitorConfig> monitorConfigsExt = new ArrayList<>();
        //如果是服务类监控，主动增加每6小时监控该服务是否正常
        for (SysMonitorConfig e : sysMonitorConfigs) {
            if (e.getTaskType().equals(TaskTypeEnum.SERVER.getType())) {
                SysMonitorConfig config = new SysMonitorConfig();
                BeanUtils.copyProperties(e, config);
                config.setId(config.getId() + Constants.TASK_NAME_EXT);
                config.setScheduledCron(Constants.TASK_EXT_CRON);
                monitorConfigsExt.add(config);
            }
        }
        sysMonitorConfigs.addAll(monitorConfigsExt);
        scheduledConfig.refresh(sysMonitorConfigs);
    }

    @Override
    public SysMonitorConfig selectOneById(String id) {
        return sysMonitorConfigMapper.selectById(id);
    }


}
